<template>
  <div class="skill-step">
    <div class="step-header">
      <h3>专业技能</h3>
      <p>请填写您的专业技能</p>
    </div>

    <div class="skill-list">
      <div 
        v-for="(skill, index) in skillList"
        :key="skill.id || index"
        class="skill-item"
      >
        <el-form 
          :model="skill"
          label-width="100px"
          class="skill-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="技能名称" prop="name">
                <el-input v-model="skill.name" placeholder="请输入技能名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="熟练程度" prop="level">
                <el-select v-model="skill.level" placeholder="请选择熟练程度" style="width: 100%">
                  <el-option
                    v-for="option in SKILL_LEVEL_OPTIONS"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="技能描述" prop="description">
            <el-input
              v-model="skill.description"
              type="textarea"
              placeholder="请输入技能描述（选填）"
              :rows="2"
            />
          </el-form-item>

          <div class="form-actions">
            <el-button @click="removeSkill(index)" v-if="skillList.length > 1">
              删除
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <div class="step-actions">
      <el-button @click="addSkill">
        <el-icon><Plus /></el-icon>
        添加技能
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存专业技能
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { skillApi, type Skill, SKILL_LEVEL_OPTIONS } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const skillList = ref<Skill[]>([])

// 监听技能变化，判断是否完成
watch(skillList, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const hasValidSkill = skillList.value.some(skill => 
    skill.name && skill.level
  )
  emit('completed', hasValidSkill)
}

// 获取技能列表
const fetchSkillList = async () => {
  loading.value = true
  try {
    const response = await skillApi.getSkillList(props.resumeId)
    const data = response.data || response
    
    if (data.results && data.results.length > 0) {
      skillList.value = data.results
    } else if (Array.isArray(data) && data.length > 0) {
      skillList.value = data
    } else {
      addSkill()
    }
  } catch (error) {
    addSkill()
  } finally {
    loading.value = false
  }
}

// 添加技能
const addSkill = () => {
  skillList.value.push({
    name: '',
    level: 'intermediate',
    description: '',
    order: skillList.value.length
  })
}

// 删除技能
const removeSkill = async (index: number) => {
  const skill = skillList.value[index]
  
  if (skill.id) {
    try {
      await skillApi.deleteSkill(props.resumeId, skill.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }
  
  skillList.value.splice(index, 1)
}

// 保存技能
const handleSave = async () => {
  saving.value = true
  try {
    for (const skill of skillList.value) {
      if (!skill.name) continue

      if (skill.id) {
        await skillApi.updateSkill(props.resumeId, skill.id, skill)
      } else {
        const response = await skillApi.createSkill(props.resumeId, skill)
        const data = response.data || response
        skill.id = data.id
      }
    }

    ElMessage.success('保存成功')
    await fetchSkillList()

  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchSkillList()
})
</script>

<style lang="scss" scoped>
.skill-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .skill-list {
    .skill-item {
      border: 1px solid var(--border-color-light);
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 20px;
      background: var(--bg-color);

      &:last-child {
        margin-bottom: 0;
      }

      .skill-form {
        .form-actions {
          text-align: right;
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid var(--border-color-extra-light);
        }
      }
    }
  }

  .step-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-extra-light);
    display: flex;
    gap: 12px;
  }
}
</style>
